import { useEffect, useCallback } from 'react';

export const useKeyboardShortcuts = (shortcuts) => {
  const handleKeyPress = useCallback((event) => {
    // 忽略输入框中的按键
    if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
      return;
    }

    const key = event.key.toLowerCase();
    const ctrl = event.ctrlKey || event.metaKey;
    const shift = event.shiftKey;
    const alt = event.altKey;

    Object.entries(shortcuts).forEach(([shortcut, callback]) => {
      const [shortcutKey, ...modifiers] = shortcut.split('+').reverse();
      
      const hasCtrl = modifiers.includes('ctrl');
      const hasShift = modifiers.includes('shift');
      const hasAlt = modifiers.includes('alt');

      if (
        key === shortcutKey.toLowerCase() &&
        ctrl === hasCtrl &&
        shift === hasShift &&
        alt === hasAlt
      ) {
        event.preventDefault();
        callback();
      }
    });
  }, [shortcuts]);

  useEffect(() => {
    document.addEventListener('keydown', handleKeyPress);
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, [handleKeyPress]);
};